package com.example.android.sip;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.widget.EditText;
import android.widget.Toast;


public class ContactsActivity extends Activity{

	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);       
		Intent intentContact = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
		
		EditText edit = new EditText(getApplicationContext());
		//startActivity(intentContact);
		startActivityForResult(intentContact, 200);
	}//onCreate
	
	@Override
	public void onActivityResult(int reqCode, int resultCode, Intent data) {
	  super.onActivityResult(reqCode, resultCode, data);
	  String name="";
	  String hasPhone="";
	  String phoneNumber="";
	  String account="";
	  String hasPhoto="";
	  int count= 0,warning=0;
	  int id = 0;
	  switch (reqCode) {
	    case (200) :
	      if (resultCode == Activity.RESULT_OK) {
	        Uri uri = data.getData();
	        Cursor cursor =  managedQuery(uri, null, null, null, null);
	        if (cursor.moveToFirst()) {
	            name = cursor.getString(cursor.getColumnIndex(Contacts.DISPLAY_NAME));
	            id = cursor.getInt(cursor.getColumnIndex(Contacts._ID));
	            hasPhone = cursor.getString(cursor.getColumnIndex(Contacts.HAS_PHONE_NUMBER));
	            hasPhoto = cursor.getString(cursor.getColumnIndex(Contacts.PHOTO_ID));
 // TODO Whatever you want to do with the selected contact name.
	        }
	        // query for telephone number
	        if ("1".equals(hasPhone)){
	        	Cursor phones = getContentResolver().query(Phone.CONTENT_URI, null,Phone.CONTACT_ID +" = "+ id,null, null);
	        	count=0;
	        	while (phones.moveToNext()) 
	        	{ 
	        		phoneNumber = phones.getString(phones.getColumnIndex(Phone.NUMBER));
	        		count++;
	        		
	        	}
	        	if (count>1) warning=1;
	        	phones.close();
	        }// TODO ELSE CASE
	        if (true){
	        	Cursor email = getContentResolver().query(Email.CONTENT_URI,null,Email.CONTACT_ID + " = " + id,null,null );
	        	count=0;
	        	while (email.moveToNext()){
	        		account= email.getString(email.getColumnIndex(Email.CONTENT_TYPE));
	        		count++;
	        	}
	        	if (count>1) warning =2;
	        	email.close();
	        }
	        if (warning>0) Toast.makeText(this, "WARNING: multiple " + ((warning==1)? "numbers":"accounts"),Toast.LENGTH_LONG).show();
	      }
	      break;
	  }
	  Toast.makeText(this,phoneNumber +"/" + account , Toast.LENGTH_LONG).show();
	  
	}
}
